package com.sanjiahantang.youjiaclient.module.apk;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.View;

import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadLargeFileListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.sanjiahantang.uilibrary.utils.Utils;
import com.sanjiahantang.youjiaclient.config.ConfigValue;
import com.sanjiahantang.youjiaclient.config.StaticValue;
import com.sanjiahantang.youjiaclient.http.BaseDelegate;
import com.sanjiahantang.youjiaclient.http.OkHttpClientManager;
import com.sanjiahantang.youjiaclient.module.apk.beans.VersionBean;
import com.sanjiahantang.youjiaclient.module.apk.views.impl.ProgressActivity;
import com.sanjiahantang.youjiaclient.utils.AppManager;
import com.sanjiahantang.youjiaclient.utils.FileUtils;
import com.sanjiahantang.youjiaclient.utils.SDCardUtils;
import com.sanjiahantang.youjiaclient.utils.SPUtils;
import com.squareup.okhttp.Request;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import static com.sanjiahantang.youjiaclient.config.SPConfig.VERSION_ID;

/**
 * Created by yan on 2017/12/1.
 * 下载管理器
 */

public class ApkDownloadUtils implements StaticValue {


    /**
     * 打开安装包
     *
     * @param fileName
     * @param context
     */

    public static void openFile(String fileName, Activity context) {
        // TODO Auto-generated method stub
        if (fileName.endsWith(".apk")) {
            if (Build.VERSION.SDK_INT >= 24) {//判读版本是否在7.0以上
                File file = new File(fileName);
                Uri apkUri = FileProvider.getUriForFile(context, "com.sanjiahantang.youjiaclient.fileprovider", file);//在AndroidManifest中的android:authorities值
                Intent install = new Intent(Intent.ACTION_VIEW);
                install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                install.setDataAndType(apkUri, "application/vnd.android.package-archive");
                context.startActivity(install);
            } else {
                Intent install = new Intent(Intent.ACTION_VIEW);
                install.setDataAndType(Uri.fromFile(new File(fileName)), "application/vnd.android.package-archive");
                install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(install);
            }
            context.finish();
        }
    }


    /**
     * checkID 0调用检测版本号接口 1调用下载地址接口
     *
     * @param context
     * @param checkID
     */
    public static void versionCheck(final Activity context, final int checkID) {
        Map<String, String> params = new HashMap<>();
        String value = "";
        if (checkID == 0) {
            value = "appCostomerVersion";
        } else {
            value = "appCostomerAddress";
        }
        params.put(KEY_CONFIGCODE, value);
        OkHttpClientManager.postAsyn(context, ConfigValue.API_URL + "/system/config/findConfigCode",
                params, new BaseDelegate.ResultCallback<VersionBean>() {

                    @Override
                    public void onError(Request request, Object tag, Exception e) {

                    }

                    @Override
                    public void onResponse(VersionBean response, Object tag) {
                        if (response == null || response.getConfigValue() == null || response.getConfigValue().isEmpty()) {
                            return;
                        }
                        //打开表单详情页面
                        if (checkID == 0) {
                            int code = Integer.valueOf(response.getConfigValue());
                            if (isUpdate(context, code)) {
                                getDownloadAddress(context, code);
                            }
                        } else {
                            //TODO
                            if (!response.getConfigValue().isEmpty()) {
                                FileUtils.deleteFile(SDCardUtils.getAPKPath(context));
                                Intent intent = new Intent(context, ProgressActivity.class);
                                intent.putExtra(StaticValue.KEY_OBJECT, response.getConfigValue());
                                context.startActivity(intent);
                            }
                        }
                    }
                });
    }


    /**
     * @param context
     * @param netCode 判断是否更新
     * @return
     */
    private static boolean isUpdate(Activity context, int netCode) {

        int currentVersion = AppManager.getAPPVersionCode(context);

        int version = (int) SPUtils.get(context, VERSION_ID, 0);

        if (netCode <= currentVersion) {
            return false;
        }

        if (netCode < version) {

            return false;
        }

        if (netCode == version) {
            String path = SDCardUtils.getAPKPath(context);
            File file = new File(path);
            if (file.exists()) {
                openFile(path, context);
                return false;
            } else {
                return true;
            }
        } else {//netCode > version回执行这里，是网络版本大于本地存储版本
            return true;
        }
    }

    /**
     * 下载最新包提示
     *
     * @param context
     */
    private static void getDownloadAddress(final Activity context, final int code) {
        Utils.showDialog(context, "提示", "请安装最新包", "", "", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Utils.dismissDialog();
                switch (view.getId()) {
                    case com.sanjiahantang.uilibrary.R.id.txtDialogCancel:
                        System.exit(0);
                        break;
                    case com.sanjiahantang.uilibrary.R.id.txtDialogSure:
                        SPUtils.put(context, VERSION_ID, code);
                        versionCheck(context, 1);
                        break;
                }
            }
        });
    }

}
